<style type="text/css" title="currentStyle">
	@import "../media/css/demo_table.css";
	@import "media/css/TableTools.css";
</style>

<script type="text/javascript" charset="utf-8" src="../media/js/jquery.dataTables.js"></script>
<script type="text/javascript" charset="utf-8" src="media/ZeroClipboard/ZeroClipboard.js"></script>
<script type="text/javascript" charset="utf-8" src="media/js/TableTools.js"></script>
<script type="text/javascript" charset="utf-8">
	$(document).ready( function () {
		/* You might need to set the sSwfPath! Something like:
		 *   TableToolsInit.sSwfPath = "/media/swf/ZeroClipboard.swf";
		 */
		$('#example').dataTable( {
			"sDom": 'T<"clear">lfrtip'
		} );
	} );
</script>
<?php
function chk_folder($filename)
{ //echo $filename;
	$fp_load = @fopen($filename, "rb");
	if ( $fp_load )
	{ 
		return true;
	}
	else
	{ 
		return false;
	}
}

function getDeviceModel($imeiNo)
{
	
		$db = new Database(DB_SERVER, DB_USER, DB_PASS, DB_DATABASE); 
		$db->connect(); 
		 $getDevName = "SELECT di_deviceModel  FROM tb_deviceinfo WHERE di_imeiId =".$imeiNo." AND di_status = 1";
		$resultRow = $db->query($getDevName);
		$deviceRecord = $db->fetch_array($resultRow);
		if($deviceRecord[di_deviceModel] != '')
			return strtolower($deviceRecord[di_deviceModel]);
		else
			return;
		
}
function gpspathFunAll($date_offline,$deviceIMEI)
{
	$path1=DATAPATH.date('d-m-Y',strtotime($date_offline))."/".$deviceIMEI.".txt";
	//$path1="http://localhost/gpsapp/data/".date('d-m-Y',strtotime($date_offline))."/352848025507217.txt";
	
	if(chk_folder($path1))
	{
		$file1 = @fopen($path1, "r");
		if($file1)
		{
			$i=0;
			while(!feof($file1))
			{
			  $data1= fgets($file1);				 
			}
			$data1 = getSortedData($data1);
			fclose($file1);
		}
		return $data1;
	}
		
}

function sec2hms($sec, $padHours=FALSE) {
    $hours_min_secs = "";
    $hours = INTVAL(INTVAL($sec) / 3600); 
    $hours_min_secs .= ($padHours) ? STR_PAD($hours, 2, "0", STR_PAD_LEFT). ':' : $hours. ':';

    $minutes = INTVAL(($sec / 60) % 60); 
   $hours_min_secs .= STR_PAD($minutes, 2, "0", STR_PAD_LEFT). ':';
    $seconds = INTVAL($sec % 60); 
    $hours_min_secs .= STR_PAD($seconds, 2, "0", STR_PAD_LEFT);
    return $hours_min_secs;
}

function addcolon($input){
  $tmp = '';
 for($i=0;$i<strlen($input);$i+=2){
  $tmp.=substr($input, $i, 2).':';
 }
 $input=substr($tmp, 0, strlen($tmp)-1);

 return $input;
}

function getTimediff($string,$ig_port_one,$ig_port_zero,$strtTime,$endTime){


$a = array();
$a = explode("#",$string);
$st1 = array();
$en1 = array();

 $start_on =$end_on='0';
 $start_off =$end_off='0';
 $i='0';
foreach($a as $key=>$str)
{

 $e=explode(',',$str);
 //$e[7]=$str;

  $geoTime = date("H:i",strtotime($e[9]));
					$curTime = explode(":",$geoTime);
					$curTime = (($curTime[0] * 60 )+ $curTime[1]);
  
if($curTime >= $strtTime && $curTime<=$endTime){


//starting of off on time
if(isset($str) && strpos($str,$ig_port_zero)!=""  &&  $start_off=='0'){
    $st1_of=substr($str,-19); 
  $start_off =1;
}
//end of ac off time
if(isset($str) && strpos($str,$ig_port_one)!=""  &&  ($start_off=='1' && $end_off!='1')){
	$dff = explode(',',$a[$i-1]);

  $en1_of=substr($a[$i-1],-19); 
 // $en1_of=substr($str,-19); 
  $end_off='1';
}


//starting of ac on time
if(isset($str) && strpos($str,$ig_port_one)!=""  &&  $start_on=='0'){
    $st1=substr($str,-19); 
  $start_on =1;
}
//end of ac on time
if(isset($str) && strpos($str,$ig_port_zero)!=""  &&  ($start_on=='1' && $end_on!='1')){
	$dff = explode(',',$a[$i-1]);

  $en1=substr($a[$i-1],-19); 
 // $en1=substr($str,-19); 
  $end_on='1';
}


	if($end_on!=0)
	{	
		$diff = strtotime($en1) - strtotime($st1);
		 if($diff>'0'){
   		  $time[$st1.'$'.date("h:i:s A",strtotime($st1)) .'&nbsp;=>&nbsp;'. date("h:i:s A",strtotime($en1))] = sec2hms($diff).'$'.'on'.'$'.$diff;
		 }
		$start_on =0;
       $end_on='0';
	}	


	if($end_off!=0)
	{	
		$diff = strtotime($en1_of) - strtotime($st1_of);
		 if($diff>'0'){
   		  $time[$st1_of.'$'.date("h:i:s A",strtotime($st1_of)) .'&nbsp;=>&nbsp;'. date("h:i:s A",strtotime($en1_of))] = sec2hms($diff).'$'.'off'.'$'.$diff;
		 }
		$start_off =0;
       $end_off='0';
	}

}
	$i++;
}


return $time;

}


if($recordUserInfo[ci_clientType] == "Client" && $recordUserInfo[ui_isAdmin] == "1")
{
	$devices_query =  "SELECT * FROM tb_deviceinfo,tb_client_subscription WHERE tcs_isActive = 1 AND tcs_deviceId = di_id AND di_clientId =".$_SESSION[clientID]." AND di_status = 1 ORDER BY di_deviceName,di_deviceId ASC";
}
else if($recordUserInfo[ci_clientType] == "Client" && $recordUserInfo[ui_isAdmin] == "0" && $recordUserInfo[ui_roleId] == "1")
{
	$devices_query = "SELECT * FROM tb_deviceinfo,tb_client_subscription WHERE tcs_isActive = 1 AND tcs_deviceId = di_id AND di_status = 1 AND di_clientId=".$_SESSION[clientID]." AND di_assignedUserId = ".$_SESSION[userID]." ORDER BY di_deviceName,di_deviceId ASC";
}
//echo $devices_query;
//$devices_query =  "SELECT * FROM tb_deviceinfo WHERE di_clientId =".$_SESSION[clientID]." AND di_status = 1 ORDER BY di_deviceName,di_deviceId ASC";
$devices_resp = mysql_query($devices_query);	


?>
<script type="text/javascript" language="javascript">


function validateMapReport()
{
  if(document.getElementById('map_device_id').value== 0 )
  { alert("Select Vehicle");  document.getElementById('map_device_id').focus();  return 0;  }
  
  if(document.getElementById('from_date').value=='')
  { alert("Select From Date"); document.getElementById('from_date').focus();  return 0;  }
  
  if(document.getElementById('to_date').value=='')
  { alert("Select To Date");  document.getElementById('to_date').focus(); return 0; }
  
	
	var t1=document.getElementById('from_date').value ;
        var t2=document.getElementById('to_date').value;

        var one_day=1000*60*60*24; 
		var x=t1.split("-");     
        var y=t2.split("-");
        var date1=new Date(x[2],(x[1]-1),x[0]);
  
        var date2=new Date(y[2],(y[1]-1),y[0]);
        var month1=x[1]-1;
        var month2=y[1]-1;
        var diff=Math.ceil((date2.getTime()-date1.getTime())/(one_day)); 
         
		 if(diff < 0){
       alert("From Date should be prior to To Date."); document.getElementById('to_date').select();return 0;

		 }
	return 1;
	
}
function sendCSVData()
{
  document.frmKiloData.submit();
}
function showFormDiv()
{
	if(document.getElementById('formDiv').style.display=='none')
	{
		document.getElementById('formDiv').style.display = 'block';
		document.getElementById('shLink').innerHTML = "Hide Form";
	}
	else
	{
		document.getElementById('formDiv').style.display = 'none';
		if(document.getElementById('shLink'))
		document.getElementById('shLink').innerHTML = "Show Form";
	}
}
function showPreloader()
{
	var returnVal = validateMapReport()
	if(returnVal == 1)
	{

		document.getElementById('popup_div').innerHTML = '<div id="loading_txt" >Loading...</div>';
		document.frm_map_filter.submit();
	}
}
function showFormDiv()
{
	if(document.getElementById('formDiv').style.display=='none')
	{
		document.getElementById('formDiv').style.display = 'block';
		document.getElementById('shLink').innerHTML = "Hide Form";
	}
	else
	{
		document.getElementById('formDiv').style.display = 'none';
		if(document.getElementById('shLink'))
		document.getElementById('shLink').innerHTML = "Show Form";
	}
}
function hidePreLoader()
{
	document.getElementById('popup_div').innerHTML = '&nbsp;';

}
jQuery(function() {

    //$("#time3, #time4").timePicker();
	 $("#time3, #time4").timePicker({
	  startTime: "12:01 AM", // Using string. Can take string or Date object.
	  endTime: "11:59 PM", // Using Date object here.
	  show24Hours: false,
	  separator: ':',
	  step: 1});    
        
    // Store time used by duration.
    var oldTime = $.timePicker("#time3").getTime();
    
    // Keep the duration between the two inputs.
    $("#time3").change(function() {
      if ($("#time4").val()) { // Only update when second input has a value.
        // Calculate duration.
        var duration = ($.timePicker("#time4").getTime() - oldTime);
        var time = $.timePicker("#time3").getTime();
        // Calculate and update the time in the second input.
        $.timePicker("#time4").setTime(new Date(new Date(time.getTime() + duration)));
        oldTime = time;
      }
    });
    // Validate.
    $("#time4").change(function() {
      if($.timePicker("#time3").getTime() > $.timePicker(this).getTime()) {
        $(this).addClass("error");
      }
      else {
        $(this).removeClass("error");
      }
    });
    
  });

$(function() {
	$( "#from_date" ).datepicker({
		changeMonth: true,
		changeYear: true,
		maxDate: 0,
		showOn: "button",
		buttonImage: "images/calendar.gif",
		buttonImageOnly: true,
		dateFormat : "dd-mm-yy"
	});
});
$(function() {
	$( "#to_date" ).datepicker({
		changeMonth: true,
		changeYear: true,
		maxDate: 0,
		showOn: "button",
		buttonImage: "images/calendar.gif",
		buttonImageOnly: true,
		dateFormat : "dd-mm-yy"
	});
});
</script>
<div id="formDiv">
<form id="frm_map_filter" name="frm_map_filter" method="post" action="" onsubmit="return validateMapReport();"> 
<table class="gridform_final" style="width:75%">
<tr><th colspan="4">Ignition Report</th></tr>
  <tr>
    <td width="15%" align="right"><span class="form_text">Select Device</span></td>
    <td width="35%" align="left" colspan="3">
        <select name="map_device_id" id="map_device_id" class="hours_select" tabindex="1" style="width:50%;" >
        <option value="0">Select Device</option>
        <?php 
        while($devices_fetch = @mysql_fetch_assoc($devices_resp)) 
        {
			$renewDate = date("d-m-Y",strtotime("-1 days ".($devices_fetch[tcs_noOfMonths]) ."months ".$devices_fetch[tcs_renewalDateFrom]));
			//echo $date_offline." <= ".date("d-m-Y",strtotime($renewDate))."<br>";
			if(strtotime(date('d-m-Y')) <= strtotime($renewDate))
			{
			if($devices_fetch[di_deviceName])
				$devName = $devices_fetch[di_deviceName];
			else
				$devName = $devices_fetch[di_deviceId];
        ?>
        <option value="<?php echo $devices_fetch[di_imeiId]; ?>" 
        <?php if($_POST[map_device_id] == $devices_fetch[di_imeiId]) echo "selected"; ?>><?php echo $devName; ?></option>
        <?php }} ?>	
        </select>
        <input type="hidden" name="curdate" id="curdate" value="<?php echo date('Y-m-d'); ?>" />
    </td>
    </tr>              
    <tr>
    <td width="15%" align="right"><span class="form_text">From Date & Time</span></td>
    <td width="35%" align="left">
    <input type="text" name="from_date" id="from_date" readonly="true" tabindex="2" size="12" value="<?php if(isset($_POST[from_date])) echo $_POST[from_date]; else echo date("d-m-Y"); ?>" style="width:140px;"/>&nbsp;
    <span><input type="text" name="time3" readonly="true" id="time3" size="7" tabindex="3" value="<?php if($_POST[time3]) echo $_POST[time3]; else echo "12:01 AM";?>" /></span>
    </td>
    <td width="15%" align="right"><span class="form_text">To Date & Time</span></td>
    <td width="35%">
    <input type="text" name="to_date" id="to_date" size="12" style="width:140px;" tabindex="4" readonly="true" value="<?php if(isset($_POST[to_date])) echo $_POST[to_date]; else echo date("d-m-Y"); ?>" />&nbsp;
    <span><input type="text" name="time4" readonly="true" id="time4" size="7" tabindex="5" value="<?php if($_POST[time4]) echo $_POST[time4]; else echo "11:59 PM";?>" /></span>
    </td>
  </tr>
  <tr>
    <td align="right" width="15%"><span class="form_text"></span></td>
    <td align="left" width="35%" colspan="3">
        
		<input type="checkbox" name="daybase" id="daybase" value="day" <?php if($_POST[daybase]!=""){echo 'checked';}?>>Total Day</td>
    </tr>
  <tr>
    <td height="33" colspan="4" style="text-align:center">
    <input type="button" name="map_filter_btn"   value="Filter" class="save_btn" tabindex="6"  onclick="showPreloader();"/>
    <input type="hidden" name="map_filter_btn" value="Filter" />
    <input type="button" name="map_cancel_btn" id="map_cancel_btn" value="Reset" class="save_btn" onclick="location.href='index.php?ch=ignition';" tabindex="7" /> 
    </td>
  </tr>
  
</table>
</form>
</div>
<div id="popup_div" style=" display:block; border:0px;" >

</div>	
	
<?php
if(isset($_POST[map_filter_btn]) && $_POST[map_filter_btn]!='')
{ 
//print_r($_POST);
?>
<div class="listofusers" align="right">&nbsp;<a href="#" class="error_strings" id="shLink" onClick="showFormDiv();">Show Form</a></div>
<div style="overflow:scroll; overflow-X:hidden;  border:1px solid #dfe9ed; border-top:0px solid #FFF; padding-top:2%">
<div id="container">			
  <div id="demo">
<table cellpadding="0" cellspacing="0" border="0" class="gridform_final" id="example">      
  <thead>
  	<tr>
        <th width="30%">Date (dd/mm/yy)</th>
        <?php if($_POST[daybase]==""){?>
		<th width="30%">From & To (Time)</th>
        <th>Time Differece in <br/>(Hours:Minutes:Seconds)</th>
		<?php }?>
        <th>Ignition</th>
       </tr>
	</thead>
    <tbody>  

<?php
	

	$sdate = $_POST[from_date];
	$edate = $_POST[to_date];
	
	$strtTime = explode(":",date("H:i",strtotime($_POST[time3])));
	$strtTime = (($strtTime[0] * 60) + $strtTime[1]);
	
	$endTime = explode(":",date("H:i",strtotime($_POST[time4])));
	$endTime = (($endTime[0] * 60) + $endTime[1]);
	
      $devmodel = getDeviceModel($_POST[map_device_id]);
/*echo strpos($devmodel,'fm2200');
exit;*/
     /* if((strpos($devmodel,'fm2100')==0 || strpos($devmodel,'fm2200')==00) || (strpos($devmodel,'fm2100')!=0 || strpos($devmodel,'fm2200')!=00)){
		  
        $ig_port_one = "[1=1]";
        $ig_port_zero = "[1=0]";
	  } else if((strpos($devmodel,'fm4200')==0 || strpos($devmodel,'fm4100')==0) || (strpos($devmodel,'fm4200')!=0 || strpos($devmodel,'fm4100')!=0)){

        $ig_port_one = "[3=1]";
        $ig_port_zero = "[3=0]";
	  } else {
         $ig_port_one = "[3=1]";
        $ig_port_zero = "[3=0]";
	  }*/
	  $ig_port_one = "[3=1]";
        $ig_port_zero = "[3=0]";

 $z = GetDays($sdate, $edate);


	if($_POST[from_date] == $_POST[to_date])
	{
		$data =  gpspathFunAll($_POST[from_date],$_POST[map_device_id]);
		
     
	   $one_pos_instr = strpos($data,$ig_port_one);
	   $zero_pos_instr = strpos($data,$ig_port_zero);


				if($zero_pos_instr!="" &&$one_pos_instr==""){
				  $finData[] = array($_POST[from_date].','.$_POST[time3] .'&nbsp;To&nbsp;'.$_POST[time4] =>'24:00:00$off$86400');

				} else if($one_pos_instr=="" && $zero_pos_instr!=""){
  				  $finData[] = array($_POST[from_date].','.$_POST[time3] .'&nbsp;To&nbsp;'. $_POST[time4] =>'24:00:00$on$86400');
				} else if($one_pos_instr=="" && $zero_pos_instr==""){
   				  $finData[] = array($_POST[from_date].','.$_POST[time3] .'&nbsp;To&nbsp;'. $_POST[time4] =>'Not connected to ac');
				}else {
					$s= getTimediff($data,$ig_port_one,$ig_port_zero,$strtTime,$endTime);
				   $finData[] = $s;
				}

	  

	}
	else
	{
		$z = GetDays($sdate, $edate);
		for($y=0; $y<count($z); $y++)
		{      $data =  gpspathFunAll($z[$y],$_POST[map_device_id]);	

				
	           $one_pos_instr = strpos($data,$ig_port_one);
	          $zero_pos_instr = strpos($data,$ig_port_zero);

			if($y == 0) 
			{
				$strtTime1 = $strtTime;
				$endTime1 = 1439;
				


				if($zero_pos_instr!="" &&$one_pos_instr==""){
				  $finData[] = array(date('d-m-Y',strtotime($z[$y])).','.$_POST[time3] .'$'. date('d-m-Y',strtotime($z[$y])).','.$_POST[time4] =>'24:00:00$off$86400');

				} else if($one_pos_instr=="" && $zero_pos_instr!=""){
  				  $finData[] = array(date('d-m-Y',strtotime($z[$y])).','.$_POST[time3] .'$'. date('d-m-Y',strtotime($z[$y])).','.$_POST[time4] =>'24:00:00$on$86400');
				} else if($one_pos_instr=="" && $zero_pos_instr==""){
   				  $finData[] = array(date('d-m-Y',strtotime($z[$y])).','.$_POST[time3] .'$'. date('d-m-Y',strtotime($z[$y])).','.$_POST[time4] =>'Not connected to ac');
				}else {
					$s= getTimediff($data,$ig_port_one,$ig_port_zero,$strtTime,$endTime);
				   $finData[] = $s;
				}

				
                 
			}
			elseif($y == count($z)-1) 
			{
				$strtTime1 = 0;
				$endTime1 = $endTime;
                
				

				if($zero_pos_instr!="" &&$one_pos_instr==""){
				  $finData[] = array(date('d-m-Y',strtotime($z[$y])).','.$_POST[time3] .'$'. date('d-m-Y',strtotime($z[$y])).','.$_POST[time4] =>'24:00:00$off$86400');

				} else if($one_pos_instr=="" && $zero_pos_instr!=""){
  				  $finData[] = array(date('d-m-Y',strtotime($z[$y])).','.$_POST[time3] .'$'. date('d-m-Y',strtotime($z[$y])).','.$_POST[time4] =>'24:00:00$on$86400');
				} else if($one_pos_instr=="" && $zero_pos_instr==""){
   				  $finData[] = array(date('d-m-Y',strtotime($z[$y])).','.$_POST[time3] .'$'. date('d-m-Y',strtotime($z[$y])).','.$_POST[time4] =>'Not connected to ac');
				}else {
					$s= getTimediff($data,$ig_port_one,$ig_port_zero,$strtTime,$endTime);
				   $finData[] = $s;
				}

				}
			elseif($y < count($z)-1) 
			{
				$strtTime1 = 0;
				$endTime1 = 1439;
				   if($zero_pos_instr!="" &&$one_pos_instr==""){
				  $finData[] = array(date('d-m-Y',strtotime($z[$y])).','.$_POST[time3] .'$'. date('d-m-Y',strtotime($z[$y])).','.$_POST[time4] =>'24:00:00$off$86400');

				} else if($one_pos_instr=="" && $zero_pos_instr!=""){
  				  $finData[] = array(date('d-m-Y',strtotime($z[$y])).','.$_POST[time3] .'$'. date('d-m-Y',strtotime($z[$y])).','.$_POST[time4] =>'24:00:00$on$86400');
				} else if($one_pos_instr=="" && $zero_pos_instr==""){
   				  $finData[] = array(date('d-m-Y',strtotime($z[$y])).','.$_POST[time3] .'$'. date('d-m-Y',strtotime($z[$y])).','.$_POST[time4] =>'Not connected to ac');
				}else {
					$s= getTimediff($data,$ig_port_one,$ig_port_zero,$strtTime,$endTime);
				   $finData[] = $s;
				}
			}
			
			
		}
	}
	

		for($x=0; $x<count($finData); $x++)
		{
            $splitData = $finData[$x];
			if($splitData==""&&$z!='1'){
				$z='1';
				echo '<tr colspan=3><td>No Data.</td></tr>';
			}
            if(count($splitData)!=""){
				/*echo '<pre>'; print_r($splitData);echo '</pre><br/>';
				exit;*/
             foreach($splitData as $key=> $f){
			  
				$y='0';
				$fr = explode('$',$key);
                
                //if(count($z)>1){$dt = date('d-m-Y',strtotime($fr[0]));}else{$dt = $fr[0];}
				if($_POST[daybase]==""){
				echo '<tr><td>'.substr($fr[0],0,10).'</td>';
				echo '<td>'.$fr[1].'</td>';

				} else if($dlf!='1'){
                 echo '<tr><td>'.$fr[0].'</td>';
				 $dlf='1';
				}

				$mb = explode('$',$f);
				

                if($_POST[daybase]==""){
                   echo '<td>'.$mb[0].'</td><td>'.$mb[1].'</td>';
				}
				 if($mb[1]=='on'){
				   $t_on += $mb[2];
				 } 

				 if($mb[1]=='off'){
                    $t_off += $mb[2];
				 }
				  if($_POST[daybase]==""){
				
				echo '</tr>';
				  }

				$y++;
			 }
		    $dlf='0';

		    if($_POST[daybase]!=""){?>
			 <td colspan='2'><b>Total Ac On Time:</b> <?php echo sec2hms($t_on);?>&nbsp;&nbsp;<b>Total Ac Off Time:</b> <?php echo sec2hms($t_off);?></td></tr>
			 <?php $t_on=$t_off='0';
		   }

		}
		}


		

	if($_POST[daybase]==""){
?>
		<tr><td colspan='2'>Total Ignition On Time: <?php echo sec2hms($t_on);?><br/>Total Ignition Off Time: <?php echo sec2hms($t_off);?></td></tr>
<?php }?>
	  
</tbody>
</table>	
</div>	
</div>
</div>
<script type="text/javascript">
showFormDiv();
hidePreLoader();
</script>	
</script>
<?php }?> 